<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/9/13 0013
 * Time: 下午 14:59
 */

namespace app\backend\controller;


use app\common\mailqueue;
use app\common\rbac;
use app\common\verify;
use app\index\model\Users;

class UsersController extends BackendBase
{
	public function add()
	{
		$this->assign("title", "新增用户");
		$this->assign("name", "新增用户");
		$group = rbac::getGroupList();
		$this->assign("group", $group);

		return $this->fetch();
	}

	public function doAdd()
	{
		$info = input("param.");
		//重复检查
		$check = db("users")->where(function ($query) use ($info) {
			$query->where("username", $info['username'])->whereOr("email", $info['email']);
		})->where("softdel", "0")->value("uid");
		if ($check <= 0) {
			$rnd1 = mt_rand();
			$rnd2 = mt_rand();
			$safekey = md5(md5($rnd1 . $info['username'] . $rnd2 . microtime() . $rnd1));
			$passsha = md5(md5($safekey . $info['password'] . $info['username'] . $safekey));
			$uuid = random(3, 21, $safekey . $info['username']);
			$extract = random(15, 13);
			$appid = random(11, 9);
			$appkey = random(13, 21);
			$data = [
				"username" => $info['username'],
				"email" => $info['email'],
				"passsha" => $passsha,
				"uuid" => $uuid,
				"safekey" => $safekey,
				"addtime" => nowtime(),
				"inviteby" => isset($inviteby) ? $inviteby : 0,
				"extract" => $extract,
				"appid" => $appid,
				"appkey" => $appkey,
				"ip" => ip(),
				"price" => PRICE,
				"uploaded" => UPLOAD,
				"downloaded" => DOWNLOAD,
				"longinv" => INV,
				"isadmin" => $info['isadmin']
			];
			//是否开启邮件确认
			if (ENABLED_VERIFY == "on") {
				$data = array_merge($data, ["confirm" => 1]);
				$jwt = verify::encode($info['email'], 86400);
				//可以自己修改邮件内容，支持HTML ↓
				$msg = "请在1天内点击链接并激活帐号：<a href=" . getWebURL() . url("/index/login/doConfirmUser", ["verify" => $jwt]) . " target='_blank'>点我点我</a>";
				//可以自己修改邮件内容，支持HTML ↑
				mailqueue::mailqueue($info['email'], "帐号激活", $msg);
			}
			$uid = db("users")->insertGetId($data);
			if (!empty($uid)) {
				jsonReturn(1, "帐号开通成功");
			} else {
				jsonReturn(0, "帐号开通失败");
			}
		} else {
			jsonReturn(0, "该账号或邮箱已存在，请重试");
		}
	}

	public function search()
	{
		$this->assign("title", "检索用户");
		$this->assign("name", "用户列表");

		return $this->fetch();
	}

	public function doSearch($type = 0)
	{
		$data = input("param.");
		$where = ["softdel" => ["=", 0]];
		$order = ["uid" => "DESC"];
		if ($type == 1) {
			$where = ["softdel" => ["=", 1]];
		} elseif ($type == 2) {
			$order = ["uid" => "ASC"];
		}
		if (isset($data['search'])) {
			$whereOr = [
				"username" => ["LIKE", "%$data[search]%"],
				"email" => ["LIKE", "%$data[search]%"],
				"uid" => ["=", $data['search']],
				"ip" => ["=", $data['search']],
				"uuid" => ["=", $data['search']]
			];
			$info = db("users")
				->alias("u")
				->join("__USER_GROUP__ ug", "u.isadmin = ug.id")
				->whereOr($whereOr)
				->where($where)
				->page($data['page'], $data['limit'])
				->order($order)
				->select();
		} else {
			$info = db("users")
				->alias("u")
				->join("__USER_GROUP__ ug", "u.isadmin = ug.id")
				->where($where)->page($data['page'], $data['limit'])->order($order)->select();
		}

		if ($info) {
			foreach ($info as $k => $v) {
				if (empty($v['ban'])) {
					$info[$k]['sban'] = "否";
				} else {
					$info[$k]['sban'] = "是";
				}
				if (empty($v['softdel'])) {
					$info[$k]['ssoftdel'] = "否";
				} else {
					$info[$k]['ssoftdel'] = "是";
				}
				if (empty($v['2fa'])) {
					$info[$k]['n2fa'] = 0;
				} else {
					$info[$k]['n2fa'] = 1;
				}
				if (empty($v['2fa'])) {
					$info[$k]['s2fa'] = "否";
				} else {
					$info[$k]['s2fa'] = "是";
				}
				if (empty($v['seal'])) {
					$info[$k]['sseal'] = "否";
				} else {
					$info[$k]['sseal'] = "是";
				}
				if ($v['sealtime'] == '0000-00-00 00:00:00') {
					$info[$k]['ssealtime'] = "N/A";
				} else {
					$info[$k]['ssealtime'] = "是";
				}
				if (!empty($v['inviteby'])) {
					$info[$k]['invitebyname'] = Users::getUserName($v['inviteby']);
				} else {
					$info[$k]['invitebyname'] = "无";
				}
				$info[$k]['nuploaded'] = getSize($v['uploaded']);
				$info[$k]['ndownloaded'] = getSize($v['downloaded']);
				$info[$k]['seedtime'] = mkPrettyTime($v['seedtime'], 1);
				$info[$k]['leechtime'] = mkPrettyTime($v['leechtime'], 1);

				//禁止一些信息的输出，用以保证帐号安全
				unset($info[$k]['appid'], $info[$k]['appkey'], $info[$k]['extract'], $info[$k]['passsha'], $info[$k]['safekey'], $info[$k]['uuid'], $info[$k]['2fakey']);
			}
			$this->jsonReturnLayUI(0, "", db("users")->count("uid"), $info);
		} else {
			$this->jsonReturnLayUI(1, "我是谁...？我在哪儿...？我在干什么...？");
		}
	}

	public function delUsers($array = [], $type = 0)
	{
		if (count($array) != count($array, 1)) {
			$info = array_column($array, "uid");
			$uid = implode(",", $info);
		} else {
			$uid = $array['uid'];
		}
		if ($type == 0) {
			$check = db("users")->whereIn("uid", $uid)->update(["softdel" => 1]);
		} else {
			$check = db("users")->whereIn("uid", $uid)->delete();
		}
		if ($check) {
			jsonReturn(1, "删除成功");
		} else {
			jsonReturn(0, "删除失败");
		}
	}

	public function editUser($uid, $k, $v)
	{
		try {
			db("users")->where("uid", $uid)->update([$k => $v]);
			userLogSave($uid, Users::getUserName(session("uid")) . " 将 " . Users::getUserName($uid) . " 的 " . getFieldName($k) . " 修改成 $v");
			jsonReturn(1, "修改成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "修改失败");
		}
	}

	public function ban()
	{
		$this->assign("title", "软删管理");
		$this->assign("name", "软删除用户列表");

		return $this->fetch();
	}

	public function licence()
	{
		$this->assign("title", "授权管理");
		$this->assign("name", "用户列表");

		return $this->fetch();
	}

	public function limit()
	{
		$this->assign("title", "限制管理");
		$this->assign("name1", "用户名限制");
		$this->assign("name2", "邮件域限制");
		$this->assign("name3", "注册邮件域限制");
		$this->assign("name4", "IP限制");
		$info = db("system_config")->field(["username", "email", "only", "ip"])->find();
		$this->assign("username", json_decode($info['username'], TRUE)['username']);
		$this->assign("email", json_decode($info['email'], TRUE)['email']);
		$this->assign("only", json_decode($info['only'], TRUE)['only']);
		$this->assign("ip", json_decode($info['ip'], TRUE)['ip']);

		return $this->fetch();
	}

	public function doLimit()
	{
		$info = input("param.");
		$key = array_keys($info);
		try {
			db("system_config")->where($key[0], "<>", "")->whereOr($key[0], "=", "")->update([$key[0] => json_encode($info)]);
			jsonReturn(1, "成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "失败");
		}
	}
}